<template>
  <div>
    <!--	header -->
    <mt-header title="我要预订" fixed>
      <router-link to="/hello" slot="left">
        <mt-button icon="back"></mt-button>
      </router-link>
    </mt-header>

    <!--	time picker -->
    <div style="margin-top: 40px;">
      <mt-cell title="预定日期" is-link @click.native="$refs.picker.open()">
        <span>{{getFormatDate}} {{getFormatWeek}} </span>
      </mt-cell>

      <mt-datetime-picker ref="picker" v-model="daySelect" type="date" year-format="{value} 年" month-format="{value} 月" date-format="{value} 日" :startDate="daytoday">
      </mt-datetime-picker>
    </div>

    <div style="border-top: honeydew 1px solid;padding-bottom: 55px; ">

      <mt-cell :title="item.timeLine" v-for="(item,index) in list" :key="index" @click.native.stop="selectIndex(item,index)" v-if="!shouldNotShow(item)">
        <span :style="'color:'+(item.openId!=me.openId?'blue':(item.status=='0'?'red':'green'))" v-if="item.doing != '暂无'">
        	{{(item.openId!=me.openId?item.doing:'您已预订')}}{{(item.status=='0'?'(审批中)':'(已通过)')}}
        </span>
        <mt-switch disabled v-model="valueMap[index].value" v-else></mt-switch>&nbsp;
        <mt-button type="danger" size="small" v-show="item.openId == me.openId" @click.native="cancel(item.id)">取消</mt-button>
      </mt-cell>
      <p style="text-align: center;">
      		<font style="font-size: 18px;color: #989898;">你看到了我的底线  (๑•́ ₃ •̀๑)！</font>
      </p>

    </div>

    <yd-popup v-model="sureBtn" position="center" width="90%">
      <mt-cell title="日期：">
        <span>{{form.date}}</span>
      </mt-cell>

      <mt-cell title="时间：">
        <span>{{form.time}}</span>
      </mt-cell>

      <mt-cell title="预订人：">
        <span>{{me.real_name}}</span>
      </mt-cell>
      <mt-cell title="原因：" is-link @click.native="sheetVisible=true">
        <span>{{slot}}</span>
      </mt-cell>
       <mt-cell title="是否需要果盘茶歇：">
        <span>
          <mt-switch v-model="form.isExt"></mt-switch>
        </span>
      </mt-cell>
       <mt-cell v-if="form.isExt">
        <span>
          <mt-field label="人数" v-model="form.extNum"></mt-field>
        </span>
      </mt-cell>

      <mt-field v-show="slot=='其他'" label="其他原因" placeholder="详细原因" v-model="form.bookReason"></mt-field>
      <!--<yd-cell-item>
          <span slot="left"></span>
          <yd-input slot="right" v-model="" max="128" required :showRequiredIcon="true" placeholder=""></yd-input>
        </yd-cell-item>-->
      <mt-button size="large" type="primary" @click.native="bookMeeting">确定</mt-button>
    </yd-popup>

    <mt-tabbar fixed>
      <mt-tab-item id="我的">
        <mt-button size="large" :type="canSure?'primary':'default'" :disabled="!canSure" @click.native="getSelectTime">确定</mt-button>
      </mt-tab-item>
    </mt-tabbar>

    <mt-actionsheet :actions="actions" cancelText="" v-model="sheetVisible">
    </mt-actionsheet>
  </div>
</template>

<script>
  import bookApi from '@/api/bookApi.js'
  import { mapState, mapMutations } from 'vuex'
  import userApi from '@/api/userApi'
  import { MessageBox } from 'mint-ui'

  var deepCopy = function(o) {
    if(o instanceof Array) {
      var n = [];
      for(var i = 0; i < o.length; ++i) {
        n[i] = deepCopy(o[i]);
      }
      return n;

    } else if(o instanceof Object) {
      var n = {}
      for(var i in o) {
        n[i] = deepCopy(o[i]);
      }
      return n;
    } else {
      return o;
    }
  }
  export default {
    computed: {
      ...mapState([
        'me'
      ]),
      getSoltDetail() {
        if(this.daySelect == null)
          this.daySelect = new Date()
        this.query.date = this.daySelect.Format("yyyy-MM-dd")
        this.form.date = this.query.date
        return this.query.date;
      },
      getFormatDate() {
        if(this.daySelect == null)
          this.daySelect = new Date()
        this.query.date = this.daySelect.Format("yyyy-MM-dd")
        this.form.date = this.query.date
        return this.query.date;
      },
      getFormatWeek() {
        if(this.daySelect == null)
          this.daySelect = new Date()
        return this.daySelect.WeekDay();
      }
    },
    data() {
      return {
        sheetVisible: false,
        actions: [{
          name: '周会',
          method: this.setWeek
        }, {
          name: '月会',
          method: this.setMonth
        }, {
          name: '季会',
          method: this.setThreeMonth
        }, {
          name: '年会',
          method: this.setYear
        }, {
          name: '其他',
          method: this.setOther
        }],
        slot: '',
        daytoday: new Date(),
        daySelect: null,
        canSure: false,
        sureBtn: false,
        pickerVisible: false,
        baseMap: [{
          value: false,
          maped: '09:00-09:30'
        }, {
          value: false,
          maped: '09:30-10:00'
        }, {
          value: false,
          maped: '10:00-10:30'
        }, {
          value: false,
          maped: '10:30-11:00'
        }, {
          value: false,
          maped: '11:00-11:30'
        }, {
          value: false,
          maped: '11:30-12:00'
        }, {
          value: false,
          maped: '12:00-12:30'
        }, {
          value: false,
          maped: '12:30-13:00'
        }, {
          value: false,
          maped: '13:00-13:30'
        }, {
          value: false,
          maped: '13:30-14:00'
        }, {
          value: false,
          maped: '14:00-14:30'
        }, {
          value: false,
          maped: '14:30-15:00'
        }, {
          value: false,
          maped: '15:00-15:30'
        }, {
          value: false,
          maped: '15:30-16:00'
        }, {
          value: false,
          maped: '16:00-16:30'
        }, {
          value: false,
          maped: '16:30-17:00'
        }, {
          value: false,
          maped: '17:00-17:30'
        }, {
          value: false,
          maped: '17:30-18:00'
        }],
        valueMap: [],
        list: [],
        form: {
          roomId: '',
          isExt: false,
          extNum: ''
        },
        query: {
          date: '2017-10-15',
          roomId: ''
        }
      }
    },
    methods: {
      ...mapMutations([
        'updateMe'
      ]),
      shouldNotShow(item) {
        var now = new Date()
        var thisDateStr = (this.getFormatDate + ' ' + item.timeLine.split('-')[0]).replaceAll('-', '/')
        var thisDate = new Date(thisDateStr)
        if(now.getTime() > thisDate.getTime())
          return true
        return false
      },
      setSlot(value) {
        if(value) {
          this.slot = value
          if(this.form && value != '其他') {
            this.form.bookReason = value
          } else {
            this.form.bookReason = ''
          }
        }
      },
      cancel(id) {
        MessageBox.confirm('确定取消会议?')
          .then(action => {
            bookApi.cancel(id)
              .then(data => {
                this.load()
                this.$dialog.toast({
                  mes: '取消成功!',
                  timeout: 2000,
                  icon: 'success',
                  callback: () => {}
                })
                this.loadData()
              })
              .catch(err => {})
          })
      },
      setWeek() {
        this.setSlot('周会')
      },
      setMonth() {
        this.setSlot('月会')
      },
      setThreeMonth() {
        this.setSlot('季会')
      },
      setYear() {
        this.setSlot('年会')
      },
      setOther() {
        this.setSlot('其他')
      },
      getSelectTime() {
        this.sureBtn = true
        if(this.valueMap != null) {
          var start = 0,
            i = 0,
            end = 0;
          for(i = 0; i < this.valueMap.length; i++) {
            if(this.valueMap[i].value) {
              start = i;
              break;
            }
          }
          for(i = this.valueMap.length - 1; i >= 0; i--) {
            if(this.valueMap[i].value) {
              end = i;
              break;
            }
          }
          this.form.time = this.valueMap[start].maped.substring(0, 5) + this.valueMap[end].maped.substring(5, this.valueMap[end].maped.length);
        }
      },
      selectIndex(item, index) {
        if(item.doing == '暂无' && !this.shouldNotShow(item)) {
          this.calculation(index, !this.valueMap[index].value)
        }
      },
      calculation(index, bool) {
        if(bool) { // 如果是要选中
          var move = 0,
            i = 0
          for(i = 0; i < this.valueMap.length; i++) {
            if(this.valueMap[i].value) {
              move = i // 找到第一个要改变的时间点
              break;
            }
          }
          if(i >= this.valueMap.length) {
            move = index // 如果没找到。那么这个元素就是第一个要改变的时间点
          }
          if(move > index) { // 如果倒着选的话	// 颠倒起始和结束
            var t = move
            t = move
            move = index
            index = t
          }
          for(i = move; i <= index; i++) {
            if(this.list[i].doing != '暂无') {
              this.$dialog.toast({
                mes: '请不要跨越已被选择时间段选择!',
                timeout: 2000,
                icon: 'error',
                callback: () => {}
              })
              return;
            }
          }
          for(i = move; i <= index; i++) {
            this.valueMap[i].value = true // 选中中间所有
          }

        } else { // 取消选中
          var move = 0,
            i = 0
          for(i = this.valueMap.length - 1; i >= 0; i--) {
            if(this.valueMap[i].value) {
              move = i // 找到第一个要改变的时间点
              break;
            }
          }
          if(i <= 0) {
            move = index // 如果没找到。那么这个元素就是第一个要改变的时间点
          }
          for(i = move; i >= index; i--) {
            this.valueMap[i].value = false // 去除选中中间所有
          }
        }
        for(i = 0; i < this.valueMap.length; i++) {
          if(this.valueMap[i].value) {
            this.canSure = true
            return;
          }
        } // 判断是否要提交按钮
        this.canSure = false
      },
      bookMeeting() {
        console.log(this.form.bookReason)
        var vm = this
        if(this.form.bookReason == '') {
          this.$dialog.toast({
            mes: '请填写预订原因!',
            timeout: 2000,
            icon: 'error',
            callback: () => {}
          })
        } else if(this.form.bookReason == undefined || this.form.bookReason == null) {
          this.form.bookReason = '暂无'
        }
        bookApi.bookBook(this.form)
          .then(data => {
            if(data == '预定成功') {
              this.$dialog.toast({
                mes: '预定申请成功!请等待审批!',
                timeout: 2000,
                icon: 'success',
                callback: () => {
                  this.sureBtn = false
                  this.load()
                  this.canSure = false
                }
              })

            } else {
              this.$dialog.toast({
                mes: '预定失败！请重试!',
                timeout: 2000,
                icon: 'error',
                callback: () => {
                  this.load()
                }
              })
            }
          })
          .catch(error => {
            this.$dialog.toast({
              mes: error.errMsg,
              timeout: 2000,
              icon: 'error',
              callback: () => {
                this.load()
              }
            })
          })
      },
      load() {
        bookApi.findDayBooks(this.query)
          .then(data => {
            this.list = data[0].timer
            console.log(this.baseMap)
            this.valueMap = deepCopy(this.baseMap) // 深克隆
          })
          .catch(err => {})
      }
    },
    mounted() {
      console.log(this.$route)
      this.form.roomId = this.$route.params.roomId
      this.query.roomId = this.$route.params.roomId
      var token = sessionStorage.getItem('token')
      if(token && !this.me.role) {
        // 获取当前用户信息
        userApi.me()
          .then(data => {
            this.updateMe(data)
          })
          .catch(errMsg => {})
      }
      this.load()
    },
    watch: {
      getFormatDate(old, cur) {
        this.load()
      }
    }
  }
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .slot1 {
    color: black;
    font-weight: 700;
  }
</style>